import re
import datetime
import time

import ddddocr
from selenium.webdriver.support import expected_conditions as ec
from mylib.main import CustomBrowser
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait


def is_software_expired():
    expiration_date = datetime.date(2099, 2, 22)
    current_date = datetime.date.today()
    if current_date >= expiration_date:
        return True
    else:
        return False


def login(driver, admin_path):
    driver.set_page_load_timeout(30)#
    # 添加页面加载策略优化
    driver.execute_cdp_cmd('Page.setAdBlockingEnabled', {'enabled': True})  # 启用广告拦截
    driver.execute_cdp_cmd('Network.setCacheDisabled', {'cacheDisabled': False})  # 启用缓存

    # 禁用图片和CSS加载（如果不需要视觉验证）
    prefs = {
        "profile.managed_default_content_settings.images": 2,  # 禁用图片
        "profile.managed_default_content_settings.stylesheets": 2  # 禁用CSS
    }


    # 新增admin_path参数
    with open(admin_path, 'r', encoding='utf-8') as file:  # 使用传入的路径
        content = file.readlines()
    my_list = [line.strip() for line in content]  # 简化列表处理
    urls = my_list[0]
    account = my_list[1]
    password = my_list[2]
    name = my_list[3]
    driver.get(urls)

    driver.maximize_window()

    time.sleep(1.5)
    try:
        driver.switch_to.alert.accept()
    except:
        pass

    try:
        driver.switch_to.alert.accept()
    except:
        pass
    try:
        time.sleep(1)
        WebDriverWait(driver, 5).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="verifyCode"]')))
        print("有验证码")
        domain,cookies,domain2, cookies2 = yes_verify_code(driver, account, password)
        return domain,cookies,domain2, cookies2
    except Exception as e:
        print("没有验证码")
        domain,cookies,domain2, cookies2= no_verifyCode(driver, account, password, name)
    return domain,cookies,domain2, cookies2


def yes_verify_code(driver, account, password):

    while True:
        WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="phisname"]'))).clear()
        WebDriverWait(driver, 10).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="phisname"]'))).send_keys(account)
        time.sleep(1)
        try:
            driver.switch_to.alert.accept()
        except:
            print('没有弹窗')


        WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="password"]'))).clear()
        WebDriverWait(driver, 10).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="password"]'))).send_keys(password)
        time.sleep(1)

        captcha_element = driver.find_element("id", "img")
        captcha_element.screenshot("captcha.png")


        ocr = ddddocr.DdddOcr()
        with open('./captcha.png', 'rb') as f:
            img_bytes = f.read()
        res = ocr.classification(img_bytes)
        WebDriverWait(driver, 10).until(ec.visibility_of_element_located(
            (By.XPATH, '//*[@id="verifyCode"]'))).clear()
        WebDriverWait(driver, 10).until(ec.visibility_of_element_located(
            (By.XPATH, '//*[@id="verifyCode"]'))).send_keys(res)
        time.sleep(1)
        WebDriverWait(driver, 10).until(ec.visibility_of_element_located(
            (By.XPATH, '//*[@id="submitBtn"]'))).click()
        print("-------------------------------------------------")
        try:
            WebDriverWait(driver, 3).until(ec.visibility_of_element_located(
                (By.XPATH, '//span[text()="健康档案"]')))
            break
        except:
            pass

    curent_url = driver.current_url

    domain_one = re.findall('(.*?)/phis/', curent_url)[0]
    cookies_one = driver.get_cookies()
    cookies_one = cookies_one[0]['value']
    time.sleep(1)

    WebDriverWait(driver, 10).until(ec.visibility_of_element_located(
        (By.XPATH, '//span[text()="健康档案"]'))).click()
    print("点击健康档案")
    try:
        WebDriverWait(driver, 5).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="dd65-ddheader"]'))).click()
    except Exception as e:
        print('没有弹窗', e)
    cookies2 = driver.get_cookies()
    cookies2 = cookies2[0]['value']
    current_url = driver.current_url
    domain2 = re.findall('(.*?)/phis/app/ehr/index', current_url)[0]

    if cookies_one:
        return domain_one, cookies_one,domain2, cookies2


def no_verifyCode(driver, account, password, name):

    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.ID, "j_username"))).send_keys(account)
    time.sleep(.5)

    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.ID, "j_password"))).send_keys(password)
    time.sleep(.5)
    try:
        WebDriverWait(driver, 3).until(ec.visibility_of_element_located((By.CLASS_NAME, "submit-btn"))).click()
    except:
        print('无需点击登录')
    time.sleep(.5)
    queqie = False
    try:
        WebDriverWait(driver, 10).until(ec.presence_of_element_located(
            (By.XPATH, f'//div[text()="{name}"]'))).click()
    except:
        queqie = True
    if queqie:
        try:
            WebDriverWait(driver, 10).until(ec.presence_of_element_located(
                (By.XPATH, f'//div[contains(text(), "{name}")]'))).click()
        except:
            pass

    print('进入科室')
    try:
        driver.switch_to.alert.accept()
    except:
        pass
    current_url = driver.current_url
    domain_one = re.findall('(.*?)/cis/', current_url)[0]
    cookies_one = driver.get_cookies()
    cookies_one = cookies_one[0]['value']
    time.sleep(1)

    WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="dd65-ddheader"]'))).click()
    driver.close()
    time.sleep(1)


    handles = driver.window_handles
    latest_handle = handles[-1]
    driver.switch_to.window(latest_handle)
    try:
        WebDriverWait(driver, 5).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="dd65-ddheader"]'))).click()
    except Exception as e:
        pass
    cookies2 = driver.get_cookies()
    cookies2 = cookies2[0]['value']

    current_url = driver.current_url
    domain2 = re.findall('(.*?)/phis/app', current_url)[0]



    if cookies_one:


        return domain_one, cookies_one,domain2, cookies2




def get_cookies(admin_path):  # 新增admin_path参数
    driver = CustomBrowser()
    domain, cookies,domain2, cookies2 = login(driver, admin_path)  # 传入路径
    driver.quit()
    print(domain, cookies,domain2, cookies2)
    return domain, cookies,domain2, cookies2
if __name__ == '__main__':
    cookie = get_cookies()
    print(cookie)